<?php
/**
 * Created by PhpStorm.
 * User: guozhen
 * Date: 16/9/30
 * Time: 上午9:35
 */
namespace library;
include_once('../vendor/autoload.php');
use Illuminate\Database\Capsule\Manager as Capsule;
class MySQL{

    public function __construct()
    {
        $this->config = parse_ini_file("../conf/config.ini", true);
        $this->tmp = parse_ini_file($this->config['db']['swoole.db'], true);
        $this->db = $this->tmp['database'];
    }

    public function initdb(){
        $capsule = new Capsule();
        $capsule->addConnection( $this->db );
        $capsule->bootEloquent();
    }

    /**
     * 定时检查数据库连接问题 mysqli_ping()
     */
    public function timeCheck(){
        swoole_timer_tick(3600000, function(){  //1hour
            $this->Checks();
        });
    }

    public function Checks(){
        $mysqli = new \mysqli($this->db['host'], $this->db['username'], $this->db['password'], $this->db['database']);

        /* check connection */
        if ($mysqli->connect_errno) {
            printf("Connect failed: %s\n", $mysqli->connect_error);
            exit();
        }

        /* check if server is alive */
        if ($mysqli->ping()) {
            printf ("Our connection is ok!\n");
        } else {
            $this->initdb();
            printf ("Error: %s\n", $mysqli->error);
        }
        $mysqli->close();
    }
}